from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from utils.webSocket import wbs
import json

custser_router = APIRouter(prefix="/api/customer-service", tags=["在线客服"])

userdict={}
servicedict={}
serid="service1"
@custser_router.websocket("/ws/{client_id}")
async def customer_service_websocket(websocket: WebSocket, client_id: str):
    """
    客服 WebSocket 连接端点 - 业务端
    
    客户端连接示例：
    ws://localhost:8000/api/customer-service/ws/user_123
    """
    await wbs.connect(websocket, client_id)
    
    try:
        await websocket.send_text("客服建立成功")
        print(client_id.find("service"))
        print(client_id)
        print(type(client_id))
        print("_______________________________________________________________")
        if client_id.find("service")==-1:
            #用户的建联
            key=client_id+serid
            userdict[key]=websocket
        else:
            print(client_id)
            #客服的建联
            servicedict[client_id]=websocket
            print(servicedict)
            print(servicedict[client_id])

        # 持续监听客户端消息
        while True:
            # 接收消息
            data = await websocket.receive_text()
            
            try:
                # 解析消息
                message_data = json.loads(data)
                msg_type = message_data.get("type", "text")
                from_id = message_data.get("from_id")
                to_id = message_data.get("to_id")
                target = message_data.get("target")  # 目标客户端ID
                content = message_data.get("content", data)

                
                # 根据消息类型处理
                if msg_type == "user_to_admin":
                    print(from_id)
                    print(to_id)
                    print(servicedict[to_id])
                    await servicedict[to_id].send_text(content)


                    
                elif msg_type == "admin_to_user":
                    print(from_id)
                    print(to_id)
                    print(userdict)
                    await userdict[to_id+from_id].send_text(content)
                    
            except json.JSONDecodeError:
                # 如果不是 JSON 格式，直接回显
                await websocket.send_text(f"Echo: {data}")
                
    except WebSocketDisconnect:
        print(f"🔌 客户端 {client_id} 主动断开连接")
        wbs.disconnect(websocket, client_id)
    except Exception as e:
        print(f"❌ WebSocket 错误 ({client_id}): {str(e)}")
        print("---------------------"+str(e))
        wbs.disconnect(websocket, client_id)


@custser_router.get("/online-clients")
async def get_online_clients():
    """获取当前在线的客户端列表（仅本服务器）"""
    return {
        "success": True,
        "online_count": len(wbs.client_connections),
        "clients": list(wbs.client_connections.keys())
    }


@custser_router.post("/send-message")
async def send_message_to_client(client_id: str, message: dict):
    """
    通过 HTTP API 发送消息到指定客户端（仅本服务器）
    
    示例请求：
    POST /api/customer-service/send-message?client_id=user_123
    {
        "type": "notification",
        "content": "您有新的消息"
    }
    """
    try:
        await wbs.send_to_client(client_id, message)
        return {
            "success": True,
            "message": f"消息已发送给 {client_id}"
        }
    except Exception as e:
        return {
            "success": False,
            "error": str(e)
        }

